<template>
  <div class="folder-item">
    <div class="folder-header" @click="handleClick" :class="{ 'active': isActive }">
      <span class="icon">{{ file.file ? '📄' : (isExpanded ? '📂' : '📁') }}</span>
      <span class="name">{{ file.name }}</span>
    </div>
    <div class="subfolders" v-if="!file.file && isExpanded">
      <FolderItem
        v-for="child in file.children"
        :key="child.path"
        :file="child"
        :expanded-folders="expandedFolders"
        :current-path="currentPath"
        @toggle="handleToggle"
        @select="handleSelect"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, computed, defineEmits } from 'vue';
import type { FolderFileInfo } from '@/dataType/fileType';

const props = defineProps({
  file: {
    type: Object as () => FolderFileInfo,
    required: true
  },
  expandedFolders: {
    type: Array,
    required: true
  },
  currentPath: {
    type: String,
    required: true
  }
});

const emit = defineEmits<{
  (e: 'toggle', path: string): void;
  (e: 'select', file: FolderFileInfo): void;
}>()

const isExpanded = computed(() => props.expandedFolders.includes(props.file.path));
const isActive = computed(() => props.currentPath === props.file.path);

const handleClick = () => {
  if (props.file.file) {
    emit('select', props.file);
  } else {
    emit('toggle', props.file.path);
  }
};

const handleToggle = (path: string) => {
  emit('toggle', path);
};

const handleSelect = (file: FolderFileInfo) => {
  emit('select', file);
};
</script>

<style scoped>
.folder-item {
  margin-bottom: 4px;
}

.folder-header {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.folder-header:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.folder-header.active {
  background-color: rgba(30, 136, 229, 0.1);
  color: #1E88E5;
  font-weight: 500;
}

.icon {
  margin-right: 8px;
  font-size: 1.2rem;
}

.name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.subfolders {
  padding-left: 24px;
  border-left: 1px dashed #ddd;
  margin-left: 8px;
}
</style>